package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.to.AttrRespTo;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.search.GulimallSearchApplication;
import com.atguigu.gulimall.search.config.ElasticsearConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.feign.ProductFeignService;
import com.atguigu.gulimall.search.service.MallSearchService;
import com.atguigu.gulimall.search.vo.SearchParamVo;
import com.atguigu.gulimall.search.vo.SearchResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.queryparser.flexible.core.builders.QueryBuilder;
import org.apache.lucene.search.TotalHits;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.w3c.dom.Attr;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    public SearchResult search(SearchParamVo param) {

        SearchResult searchResult = null;

        SearchRequest searchRequest = buildSearchRequrest(param);

        try {
            SearchResponse response = restHighLevelClient.search(searchRequest, ElasticsearConfig.COMMON_OPTIONS);
            //把响应的请求封装成我们需要的数据
            searchResult = buildSearchResult(response, param);
        } catch (IOException e) {
            e.printStackTrace();
        }


        return searchResult;
    }

    /**
     * 准备检索请求
     * #模糊匹配、过滤（按照属性、分类、品牌、价格区间、库存）、排序、分页、高亮、聚合分析
     *
     * @param param
     * @return
     */
    private SearchRequest buildSearchRequrest(SearchParamVo param) {

        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //1.构建bool Query
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        //1.1 构建must
        if (!StringUtils.isEmpty(param.getKeyword())) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", param.getKeyword()));
        }

        //1.2 构建filter
        //1.2.1 三级分类查询
        if (param.getCatalog3Id() != null) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3Id()));
        }
        //1.2.2 品牌id查询
        if (param.getBrandId() != null && param.getBrandId().size() > 0) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
        }
        //1.2.3 按照属性查询
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            for (String attrStr : param.getAttrs()) {
                BoolQueryBuilder nestedBool = QueryBuilders.boolQuery();
                String[] s = attrStr.split("_");
                String attrId = s[0];//检索的属性id
                String[] attrValue = s[1].split(":");//检索需要的值
                nestedBool.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedBool.must(QueryBuilders.termsQuery("attrs.attrValue", attrValue));
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBool, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }
        //1.2.4按照库存是否有查询
        if (param.getHasStock() == null || param.getHasStock() == 1) {
            boolQuery.filter(QueryBuilders.termsQuery("hasStock", true));
        }
        //1.2.5 按照价格区间检索
//        if (!StringUtils.isEmpty(param.getSkuPrice())) {
//            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
//
//            String skuPrice = param.getSkuPrice();
//            String[] price = skuPrice.split("_");
//            System.out.println(price.length);
//            if (price.length == 2) {
//                int from = StringUtils.isEmpty(price[0]) ? 0 : Integer.parseInt(price[0]);
//                int to = Integer.parseInt(price[1]);
//                rangeQuery.gte(from).lte(to);
//            }
//            if (price.length == 1) {
//                int from = StringUtils.isEmpty(price[0]) ? 0 : Integer.parseInt(price[0]);
//                rangeQuery.gte(from);
//            }
//            boolQuery.filter(rangeQuery);
//        }
        //2.1 排序
        if (!StringUtils.isEmpty(param.getSort())) {
            String sort = param.getSort();
            String[] s = sort.split("_");
            sourceBuilder.sort(s[0], SortOrder.fromString(s[1]));
        }
        //2.2 分页 pageSize
        if (param.getPageNum() == null) {
            param.setPageNum(0);
        }
        sourceBuilder.from((param.getPageNum() - 1 > 0 ? param.getPageNum() - 1 : 0) * EsConstant.PRODUCT_PAGESIZE);
        sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);


        //2.3 高亮
        if (!StringUtils.isEmpty(param.getKeyword())) {
            HighlightBuilder builder = new HighlightBuilder();
            builder.field("skuTitle");
            builder.preTags("<b style='color:red'>");
            builder.postTags("</b>");
            sourceBuilder.highlighter(builder);
        }

        sourceBuilder.query(boolQuery);

        //3.聚合分析
        //TODO 3.1品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg").field("brandId").size(50);
        //3.1品牌聚合的子聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));

        sourceBuilder.aggregation(brand_agg);

        //TODO 3.2分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        //3.2 分类聚合的子聚合
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));

        sourceBuilder.aggregation(catalog_agg);

        //==============================================================================================================
        //TODO 3.3属性聚合
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");//属性聚合的子聚合
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName"));//属性聚合的子聚合的子聚合(Name)
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue"));//属性聚合的子聚合的子聚合(Value)
        attr_agg.subAggregation(attr_id_agg);

        sourceBuilder.aggregation(attr_agg);

        System.out.println("构建的DSL语句->:" + sourceBuilder.toString());
        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);

        return searchRequest;
    }

    /**
     * 构建我们需要的数据
     *
     * @param response param
     * @return
     */
    private SearchResult buildSearchResult(SearchResponse response, SearchParamVo param) {
        SearchResult result = new SearchResult();
        //1.返回当前所查询到的商品
        SearchHits hits = response.getHits();//hits的集合
        List<SkuEsModel> list = new ArrayList<>();
        if (hits.getHits() != null && hits.getHits().length > 0) {
            for (SearchHit hit : hits) {
                String source = hit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(source, SkuEsModel.class);
                if (!StringUtils.isEmpty(param.getKeyword())) {
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String title = skuTitle.getFragments()[0].string();
                    skuEsModel.setSkuTitle(title);
                }
                list.add(skuEsModel);
            }
        }
        result.setProducts(list);

        Aggregations aggregations = response.getAggregations();//拿到聚合信息
        //2.当前商品所涉及到的所有属性信息
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attr_agg = aggregations.get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            //1.设置属性id
            long id = bucket.getKeyAsNumber().longValue();
            attrVo.setAttrId(id);
            //2.设置属性名称
            ParsedStringTerms attr_name_agg = bucket.getAggregations().get("attr_name_agg");
            String name = attr_name_agg.getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(name);
            //3.设置属性值
            List<String> attrValueAgg = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets().stream().map((item) -> {
                String keyAsString = item.getKeyAsString();
                return keyAsString;
            }).collect(Collectors.toList());
            attrVo.setAttrValue(attrValueAgg);
            attrVos.add(attrVo);
        }
        result.setAttrs(attrVos);

        //3.当前商品所涉及到的所有品牌信息
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brand_agg = aggregations.get("brand_agg");
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            //1.得到品牌id
            long value = bucket.getKeyAsNumber().longValue();
            brandVo.setBrandId(value);
            //2.得到品牌名称
            ParsedStringTerms brand_name_agg = bucket.getAggregations().get("brand_name_agg");
            String name = brand_name_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(name);
            //3.得到品牌图片
            ParsedStringTerms brand_img_agg = bucket.getAggregations().get("brand_img_agg");
            String img = brand_img_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(img);

            brandVos.add(brandVo);
        }
        result.setBrands(brandVos);

        //4.当前商品所涉及到的所有分类信息
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        ParsedLongTerms catalog_agg = aggregations.get("catalog_agg");
        for (Terms.Bucket bucket : catalog_agg.getBuckets()) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            //1.得到分类id
            long value = bucket.getKeyAsNumber().longValue();
            catalogVo.setCatalogId(value);
            //2.得到分类名称
            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");//拿到子聚合
            String name = catalog_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(name);

            catalogVos.add(catalogVo);
        }
        result.setCatalogs(catalogVos);

        //5.分页信息-当前页码
        result.setPageNum(param.getPageNum());
        //5.1总记录数
        Long totalCount = hits.getTotalHits().value;
        result.setTotal(totalCount);
        //5.2总页码
        int totalPage = (int) (totalCount % EsConstant.PRODUCT_PAGESIZE == 0 ? totalCount / EsConstant.PRODUCT_PAGESIZE : (totalCount / EsConstant.PRODUCT_PAGESIZE + 1));
        result.setTotalPages(totalPage);
        //6.页码数组
        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= totalPage; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);

        //7.构建面包屑导航功能 TODO result 里面已经封装了 attrs ，不需要远程调用
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            List<SearchResult.NavVo> navVos = param.getAttrs().stream().map(attr -> {
                //7.1分析每一个attr传来的页面参数值
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                String[] s = attr.split("_");
                result.getAttrIds().add(Long.valueOf(s[0]));
                for (SearchResult.AttrVo attrVo : result.getAttrs()) {
                    if (attrVo.getAttrId() == Integer.parseInt(s[0])) {
                        navVo.setNavName(attrVo.getAttrName());
                    }
                }
                navVo.setNavValue(s[1]);
                String encode = null;
                try {
                    encode = URLEncoder.encode(attr, "UTF-8");
                    encode = encode.replace("+", "%20");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                String replace = param.getQueryString().replace("&attrs=" + encode, "");
                replace = replace.replace("attrs=" + attr, "");
                navVo.setLink("http://search.gulimall.com/list.html?" + replace);
                return navVo;
            }).collect(Collectors.toList());
            result.setNavs(navVos);
        }
        //面包屑导航 -- 品牌
        if (param.getBrandId() != null && param.getBrandId().size() > 0) {
            List<SearchResult.NavVo> navs = result.getNavs();
            param.getBrandId().stream().map(brandId -> {
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                navVo.setNavName("品牌");
                for (SearchResult.BrandVo brand : result.getBrands()) {
                    if (brand.getBrandId().intValue() == brandId) {
                        navVo.setNavValue(brand.getBrandName());
                    }
                }
                String encode = null;
                try {
                    encode = URLEncoder.encode(String.valueOf(brandId), "UTF-8");
                    encode = encode.replace("+", "%20");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                String replace = param.getQueryString().replace("&brandId=" + encode, "");
                replace = replace.replace("brandId=" + encode, "");
                navVo.setLink("http://search.gulimall.com/list.html?" + replace);
                navs.add(navVo);
                return navVo;
            }).collect(Collectors.toList());
        }
        //价格区间筛选 TODO 取消对es的价格筛选
        if (!StringUtils.isEmpty(param.getSkuPrice())) {
            String[] s = param.getSkuPrice().split("_");
            if (s.length == 2) {
                //""_x || a_b
                int from = StringUtils.isEmpty(s[0]) ? 0 : Integer.parseInt(s[0]);
                int to = Integer.parseInt(s[1]);
                List<SkuEsModel> pro_af = result.getProducts().stream().filter(e -> {
                    if (e.getSkuPrice().intValue() > from && e.getSkuPrice().intValue() < to) {
                        return true;
                    } else {
                        return false;
                    }
                }).collect(Collectors.toList());
                result.setProducts(pro_af);
            }
            if (s.length == 1) {
                int from = Integer.parseInt(s[0]);
                List<SkuEsModel> pro_af = result.getProducts().stream().filter(e -> {
                    if (e.getSkuPrice().intValue() > from) {
                        return true;
                    } else {
                        return false;
                    }
                }).collect(Collectors.toList());
                result.setProducts(pro_af);
            }
        }

        return result;
    }
}
